//工具函数库，仔仔编写。
var sum = 0;
let _tool = {
	//获取书架数据
	async GetBookListData() {
		try {
			const value = uni.getStorageSync('bookshelf_list');
			if (value) {
				return value;
			}
		} catch (e) {
			return '';
		}
	},
	//加入到书架
	async AddBookListData(data) {
		let BookList = await this.GetBookListData();
		if (BookList == "" || BookList == null || BookList == undefined) {
			let newArr = [];
			newArr.push(data);
			await this.AddBookListStorage(newArr);
		} else {
			let BookID = await this.GetBookListID(data.id);
			if (BookID == false) {
				BookList.push(data);
				await this.AddBookListStorage(BookList);
			}
		}
	},
	//更新书架信息
	async UpBookListData(data) {
		let BookList = await this.GetBookListData();
		console.log(11)
		if (BookList == "" || BookList == null || BookList == undefined) {

		} else {
			let BookID = false;
			for (let i = 0; i < BookList.length; i++) {
				if (BookList[i].name == data.name) {
					BookList[i].id = data.id
					BookList[i].sid = data.sid
					BookList[i].page = data.page
					BookList[i].index = data.index
					BookList[i].name = data.name
					BookList[i].title = data.title
					BookList[i].img = data.img
					BookList[i].data = data.data
					BookList[i].list = data.list
					BookID = true;
				}
			}
			if (BookID) {
				await this.AddBookListStorage(BookList);
			}
		}
	},
	//加入到书架数据
	async AddBookListStorage(data) {
		try {
			uni.setStorageSync('bookshelf_list', data);
		} catch (e) {
			// error
		}
	},
	//书架中是否已经存在
	async GetBookListID(NAME) {
		let BookList = await this.GetBookListData();
		if (BookList == "" || BookList == null || BookList == undefined) {
			return false;
		} else {
			let state = false;
			for (let i = 0; i < BookList.length; i++) {
				if (BookList[i].name == NAME) {
					state = true;
				}
			}
			return state;
		}
	},
	//删除书籍
	async DelBookList(BookID) {
		let BookList = await this.GetBookListData();
		if (BookList == "" || BookList == null || BookList == undefined) {
			return false;
		} else {
			let newArr = [];
			for (let i = 0; i < BookList.length; i++) {
				if (BookID.includes(BookList[i].id) == false) {
					newArr.push(BookList[i]);
				}
			}
			await this.AddBookListStorage(newArr);
		}
	},
	//清理缓存
	async clearStorage() {
		try {
			uni.setStorageSync('bookshelf_list', []);
			// uni.clearStorageSync();
		} catch (e) {
			// error
		}
	},
	async iszifu(data, url, id) {

		//console.log(sid)
		if (data.body_furl.indexOf("{{key1}}") != -1) {
			let ui = data.body_furl.replace("{{key1}}", url)
			return ui;
		}
		if (data.body_furl.indexOf("{{key1}}") != -1) {
			return data.body_furl.replace("{{key}}", id) + url;
		}
		return false
	},
	//获取书籍内容
	async GetReadContentData(SourceCode, data, url, id, sid) {




		var Content = this.replacet(await this.GetInterceptTheSpecifiedString(SourceCode, data.book_data));

		if (data.book_body) {


			let sid = await this.GetInterceptTheSpecifiedString(SourceCode, data.book_body)

			if (sid) {
				//console.log(sid, data.book_body)
				let urlf = await this.iszifu(data, sid, id)
				console.log(urlf)
				if (urlf.indexOf('_') != -1) {
					
					let cont = await this.fen_url(urlf, data, id)

					Content = Content + cont;
					
				}
			}




		} else {

			if (data.book_limit) {
				let limit = this.replacet(await this.GetInterceptTheSpecifiedString(SourceCode, data
					.book_limit));
				let page = this.replacet(await this.GetInterceptTheSpecifiedString(SourceCode, data
					.book_page));

				for (let i = 1; i < limit; i++) {

					Content = Content + this.replacet(await this.GetInterceptTheSpecifiedString(await this
						.body_url(
							page, data), data.book_data));

				}
			}

		}


		//return
		if (data.book_regular) {

			let str = data.book_regular.split('$');
			for (let s = 0; s < str.length; s++) {
				let arr = Content.split(str[s]);
				let res = [...new Set(arr)].join('');
				Content = res
			}

		}
		var burl = data.book_url.substr(data.book_url.indexOf(':') + 3).replace('/', '');
		var abc = this.strChange(Content)
		
		var a = abc.replace(data.book_name, ''); //去除行尾空格
		var b = a.replace(/<script.*?>.*?<\/script>/ig, '').replace(url, '').replace(data.book_url, '')
			.replace(
				burl, '');
		var c = b.replace(/(\\n|\\r|\\r\\n|↵)/g, "<p></p>")
		//console.log(c.trim())
		return c.trim();
	},
	async fen_url(url, data, id) {
		 
		let _this = this;
		// #ifdef MP || H5
		let config= uni.getStorageSync('config')
		let das={}
		return new Promise(function(resolve, reject) {
			das.url=url
			das.method= "GET"
			uni.request({
				url: config.wx_http_url,
				data: das,
				method:"POST",
				success: async re => {
					var ds = ''
		
					if (re.data) {
		
		
		ds = await _this.GetInterceptTheSpecifiedString(re.data,data.book_data);
					
		let dataurl = await _this.GetInterceptTheSpecifiedString(re.data, data.book_body)
		
						if (dataurl) {
							let urlf = await _this.iszifu(data, dataurl, id)
							if (urlf.indexOf("_") != -1) {
								await _this.fen_url(urlf, data)
							}
		
						}
						
							resolve(ds)
						//console.log(ds)
		
					}
		
				
				},
				fail(e) {
					reject('')
				}
			});
		});
		 // #endif
		 // #ifdef APP-NVUE
		 
		return new Promise(function(resolve, reject) {

			uni.request({
				url: url,
				success: async re => {
					var ds = ''

					if (re.data) {


		ds = await _this.GetInterceptTheSpecifiedString(re.data,data.book_data);
					
		let dataurl = await _this.GetInterceptTheSpecifiedString(re.data, data.book_body)

						if (dataurl) {
							let urlf = await _this.iszifu(data, dataurl, id)
							if (urlf.indexOf("_") != -1) {
								await _this.fen_url(urlf, data)
							}

						}
						
							resolve(ds)
						//console.log(ds)

					}

				
				},
				fail(e) {
					reject('')
				}
			});
		});
		 // #endif
		
		
	},
	strChange(str) {

		return str.toLowerCase();

	},
	async body_url(page, data) {
		let url = data.body_url.replace("{{key1}}", page);
		
		// #ifdef MP || H5
		let config= uni.getStorageSync('config')
		let das={}
		return new Promise(function(resolve, reject) {
			das.url=url
			das.method= "GET"
			uni.request({
				url: config.wx_http_url,
				data: das,
				method:"POST",
				success: async re => {
							console.log(re)
				
							resolve(re.data)
						}
					});
				});
		// #endif
		// #ifdef APP-NVUE
		return new Promise(function(resolve, reject) {
			uni.request({
				url: url,
				success: async re => {
					console.log(re)

					resolve(re.data)
				}
			});
		});
		// #endif
	},
	//首页
	async IndexData(SourceCode, data) {

		let arr = data.shu_index.split("$$$");
		if (arr.length != 18) {
			return false;

		}
		let item = {
			NewArr: [],
			bookArr: []
		}
		let BookCode = await this.GetInterceptTheSpecifiedString(SourceCode, arr[0]);
		let liArr = BookCode.split(arr[1]);
		let bookArr = [];
		for (let i = 0; i < liArr.length; i++) {
			if (liArr[i]) {
				let idView = await this.GetInterceptTheSpecifiedString(liArr[i], arr[2]);
				let img = await this.GetInterceptTheSpecifiedString(liArr[i], arr[3]);
				let id = await this.GetInterceptTheSpecifiedString(liArr[i], arr[4]);
				if (idView) {

					let name = idView;
					let newJson = {
						id: id,
						name: name,
						img: img
					};
					bookArr.push(newJson);
				}
			}
		}

		let BooksCode = await this.GetInterceptTheSpecifiedString(SourceCode, arr[5]);
		let linoeArr = BooksCode.split(arr[6]);
		let NewArr = [];
		for (let i = 0; i < linoeArr.length; i++) {
			if (linoeArr[i]) {
				let idView = await this.GetInterceptTheSpecifiedString(linoeArr[i], arr[7]);
				let img = await this.GetInterceptTheSpecifiedString(linoeArr[i], arr[8]);
				let id = await this.GetInterceptTheSpecifiedString(linoeArr[i], arr[9]);
				let intro = await this.GetInterceptTheSpecifiedString(linoeArr[i], arr[10]);
				let categoryName = await this.GetInterceptTheSpecifiedString(linoeArr[i], arr[
					11]);
				let font = await this.GetInterceptTheSpecifiedString(linoeArr[i], arr[12]);
				let dec = await this.GetInterceptTheSpecifiedString(linoeArr[i], arr[13]);
				if (idView) {

					let name = idView;
					let newJson = {
						id: id,
						name: name,
						img: img,
						intro: intro,
						categoryName: categoryName,
						font: font,
						dec: dec
					};
					NewArr.push(newJson);
				}
			}
		}

		let bannerCode = await this.GetInterceptTheSpecifiedString(SourceCode, arr[14]);
		let BanArr = bannerCode.split(arr[15]);
		let BannerArr = [];
		for (let i = 0; i < BanArr.length; i++) {
			if (BanArr[i]) {
				let img = await this.GetInterceptTheSpecifiedString(BanArr[i], arr[16]);
				let name = await this.GetInterceptTheSpecifiedString(BanArr[i], arr[17]);
				if (img) {
					// if(img){
					// if (img.indexOf("http")!=0) {
					//    img= data.book_url+img 
					// } 
					// }
					let barJson = {
						image: img,
						name: name
					};
					BannerArr.push(barJson);
				}
			}
		}
		item.NewArr = NewArr
		item.BookArr = bookArr
		item.BannerArr = BannerArr


		return item

	},
	//分级章节
	async zhang_list(url) {
		// #ifdef MP || H5
		let config= uni.getStorageSync('config')
		let das={}
		return new Promise(function(resolve, reject) {
			das.url=url
			das.method= "GET"
			console.log(das.url,'----')
			uni.request({
				url: config.wx_http_url,
				data:das,
				timeout: 6000,
				method: 'POST',
				sslVerify: false,
				success: (res) => {
					resolve(res.data);
				},
				fail(e) {
					reject(e)
				},
				complete(e) {
					//console.log('complete', e)
				}
			});
		});
		// #endif
		// #ifdef APP-NVUE
		return new Promise(function(resolve, reject) {
			uni.request({
				url: url,
				timeout: 6000,
				method: 'GET',
				sslVerify: false,
				success: (res) => {
					resolve(res.data);
				},
				fail(e) {
					reject(e)
				},
				complete(e) {
					//console.log('complete', e)
				}
			});
		});
// #endif

	},
	//详情数据
	async DetailsData(SourceCode, data, id) {
		let zj = this.replaces(await this.GetInterceptTheSpecifiedString(SourceCode,
			data.zhang_link));


		let DetailsArr = {};
		let BookCode = await this.GetInterceptTheSpecifiedString(SourceCode, data
			.rand_content);
		let bookid = this.replaces(await this.GetInterceptTheSpecifiedString(SourceCode,
			data.rand_id));
		var book_id = bookid ? bookid : id;

		let author = this.replaces(await this.GetInterceptTheSpecifiedString(BookCode,
			data.rand_author));
		let name = this.replaces(await this.GetInterceptTheSpecifiedString(BookCode,
			data.rand_name));
		let img = this.replaces(await this.GetInterceptTheSpecifiedString(BookCode, data
			.rand_img));
		if (img) {
			if (data.img_url) {
				img = data.img_url + img
			} else if (img.indexOf("http") != 0) {
				img = data.book_url + img
			}
		}


		let sort = this.replaces(await this.GetInterceptTheSpecifiedString(BookCode,
			data.rand_sort));
		let state = this.replaces(await this.GetInterceptTheSpecifiedString(BookCode,
			data.rand_state));
		let time = this.replaces(await this.GetInterceptTheSpecifiedString(BookCode,
			data.rand_time));
		let news = this.replaces(await this.GetInterceptTheSpecifiedString(BookCode,
			data.rand_state));
		let intro = this.replaces(this.replaces(await this
			.GetInterceptTheSpecifiedString(BookCode, data
				.rand_intro)));
		let newData = {
			id: book_id,
			img: img,
			name: name,
			author: author,
			sort: sort,
			intro: intro,
			state: state,
			time: time,
			news: news
		};

		DetailsArr.data = newData;
		if (data.zhang_url) {
			let urllike = data.zhang_url.replace("{{key}}", id);
			urllike = data.zhang_url.replace("$$", Math.round(parseInt(id) /
				1000)); //检索千分之一换算
			let zj = await this.GetInterceptTheSpecifiedString(SourceCode, data
				.zhang_link);
			let zhang_link = zj ? urllike + zj : urllike

			SourceCode = await this.zhang_list(zhang_link);
		}
		//console.log(newData);
		let ListView = await this.GetInterceptTheSpecifiedString(SourceCode, data
			.zhang_content);

		let liArr = ListView.split(data.zhang_list);
		let NewArr = [];
		for (let i = 0; i < liArr.length; i++) {
			if (liArr[i]) {
				let idView = await this.GetInterceptTheSpecifiedString(liArr[i], data
					.zhang_id);

				if (idView) {

					let url = data.body_url.replace("{{key}}", book_id);

					url = url.replace("{{key1}}", idView);
					let id = idView;

					let name = this.replaces(await this.GetInterceptTheSpecifiedString(
						liArr[i], data
						.zhang_name));
					let link = url;
					let newJson = {
						id: i,
						sortid: id.replace(/[^\d]/g, ""),
						chapterId: id,
						name: name.replace("\n ", ''),
						link: link
					};
					NewArr.push(newJson);
				}
			}
		}

		DetailsArr.list = NewArr;

		return DetailsArr;
	},
	//搜索结果数据
	async searchData(SourceCode, data) {

		//uni.showLoading({title: '处理中...'});
		let liCode = await this.GetInterceptTheSpecifiedString(SourceCode, data
			.search_content); //搜索区间内容

		let liArr = liCode.split(data.search_gz ? data.search_gz : "<a>");

		let searchArr = [];
		for (let i = 0; i < liArr.length; i++) {
			if (liArr[i]) {
				let id = await this.GetInterceptTheSpecifiedString(liArr[i], data
					.book_id);
				if (id) {

					let img = this.replaces(await this
						.GetInterceptTheSpecifiedString(liArr[i], data
							.search_img));
					if (img) {
						if (data.img_url) {

							img = data.img_url + img
						} else if (img.indexOf("http") != 0) {
							img = data.book_url + img
						}
					}
					let name = this.replaces(await this
						.GetInterceptTheSpecifiedString(liArr[i], data
							.search_name));
					let author = this.replaces(await this
						.GetInterceptTheSpecifiedString(liArr[i], data
							.search_author));
					let sort = this.replaces(await this
						.GetInterceptTheSpecifiedString(liArr[i], data
							.search_sort));
					let introduceView = await this.GetInterceptTheSpecifiedString(
						liArr[i], data
						.search_introduce);
					let introduce = this.replaces(await this
						.GetInterceptTheSpecifiedString(liArr[i], data
							.search_introduce));
					let search_chapter = this.replaces(await this
						.GetInterceptTheSpecifiedString(liArr[i], data
							.search_chapter));
					let newJson = {
						id: id,
						img: img,
						name: name,
						author: author,
						sort: sort,
						introduce: introduce,
						source: data,
						chapter: search_chapter,
						list: []
					};
					searchArr.push(newJson);
				}
			}
		}
		uni.hideLoading();
		return searchArr;
	},
	//截取指定字符串
	async GetInterceptTheSpecifiedString(str, data) {

		if (str.toString() === '[object Object]') {

			str = JSON.stringify(str)

		}

		let arr = data.split("$");
		let firstStr = arr[0]
		let secondStr = arr[1]
		// let bl = "\/" + firstStr + "(\S*)" + secondStr + "\/"
		// console.log(bl)
		// let subSecondStr = str.match(bl);
		// console.log(str);

		if (str == "" || str == null || str == undefined) { // "",null,undefined
			return "";
		}

		if (str.indexOf(firstStr) < 0) {

			return '';
		}

		if (str) {

			var subFirstStr = str.substring(str.indexOf(firstStr) + firstStr.length, str.length);
			//console.log(subFirstStr)
			var subSecondStr = subFirstStr.substring(0, subFirstStr.indexOf(secondStr));


		}


		return subSecondStr;
	},
	replaces(msg) {

		var msg = msg.replace(/<\/?[^>]*>/g, ''); //去除HTML Tag
		var msg = msg.replace(/[|]*\n/, ''); //去除行尾空格
		var msgx = msg.replace(/&npsp;/gi, ''); //去掉npsp

		return msgx;
	},
	replacet(str) {
		var str = str.replace(/<\/?br[^>]*>/gi, '<p>')

		var str = str.replace(/<\/?p[^>]*>/gi, '<p>')
		var str = str.replace(/&nbsp;/gi, '&nbsp;'); //去掉npsp
		var str = str.replace(/\s*/g, "");
		var str = str.replace(/\r|\n/ig, "")

		let arr = str.split('//');
		let res = [...new Set(arr)].join('');

		return res;
	},
	//获取字符串的真实长度（字节长度）
	strLeng(str) {
		if (str) {
			let len = str.length,
				truelen = 0;
			for (let x = 0; x < len; x++) {
				if (str.charCodeAt(x) > 128) {
					truelen += 2;
				} else {
					truelen += 1;
				}
			}
			return truelen;
		} else {
			return 0;
		}
	}
};

export default _tool;